package com.daervin.svc.common.utils;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author daervin
 * @version 1.0.0
 * @since 1.0.0
 */
public class FileUtil {

    private FileUtil() {
    }

    public static boolean downloadSaveFile(String fileUrl, String filePath) {
        InputStream in = null;
        OutputStream out = null;
        try {
            URL url = new URL(fileUrl);
            URLConnection connection = url.openConnection();
            connection.setConnectTimeout(5000);

            in = connection.getInputStream();
            byte[] bs = new byte[1024];
            int len;
            out = new FileOutputStream(filePath);
            while ((len = in.read(bs)) != -1) {
                out.write(bs, 0, len);
            }
        } catch (Exception e) {
            return false;
        } finally {
            try {
                out.flush();
                out.close();
                in.close();
            } catch (IOException e) {
                return false;
            }
        }
        return true;
    }

    public static boolean dropAllFile(String folder) {
        File file = new File(folder);
        if (!file.exists() || !file.isDirectory()) {
            return false;
        }
        String[] list = file.list();
        if (list == null || list.length <= 0) {
            return false;
        }
        for (String tmp : list) {
            File tmpFile = new File(folder + tmp);
            if (tmpFile != null && tmpFile.isFile()) {
                tmpFile.delete();
            }
        }
        return true;
    }

}
